import 'dart:convert';
import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart' ;
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:install_plugin/install_plugin.dart';
import 'package:mfkb/event/RouteEvent.dart';
import 'package:mfkb/pages/fun.dart' ;
import 'package:mfkb/pages/fun/schoolFun/Broadband.dart';
import 'package:mfkb/pages/fun/schoolFun/DriverSchool.dart';
import 'package:mfkb/pages/fun/schoolFun/Electricty.dart';
import 'package:mfkb/pages/fun/schoolFun/Exam.dart';
import 'package:mfkb/pages/fun/schoolFun/PhoneBill.dart';
import 'package:mfkb/pages/fun/schoolFun/Relation.dart';
import 'package:mfkb/pages/fun/schoolFun/Score.dart';
import 'package:mfkb/pages/login.dart';
import 'package:mfkb/pages/root.dart';
import 'package:mfkb/pages/userinfo.dart';
import 'package:mfkb/util/HttpUtil.dart';
import 'package:package_info/package_info.dart';
import 'package:path_provider/path_provider.dart';
import 'package:toast/toast.dart';
import 'package:url_launcher/url_launcher.dart';
import 'config/Config.dart';
import 'package:shared_preferences/shared_preferences.dart';

import 'package:permission_handler/permission_handler.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  // 获取用户登录信息，基础配置信息
  Config().init(await SharedPreferences.getInstance()) ;
  runApp(MaterialApp(
    title:"觅风课表" ,
    routes: {
      "login":(context) => LoginWidge() ,
      "home":(context) => FunWidget() ,
      "score":(context) => Score() ,
      "electricty":(context) => Electricty() ,
      "exam":(context) => Exam() ,
      "relation":(context) => Relation() ,
      "phone":(context) => PhoneBill() ,
      "driver":(context) => DriverSchool() ,
      "broad":(context) => Broadband() 
    },
    home:MyApp()
  )) ;
  if(Platform.isAndroid){ 
    SystemUiOverlayStyle systemUiOverlayStyle =
    SystemUiOverlayStyle(statusBarColor: Colors.transparent);
    SystemChrome.setSystemUIOverlayStyle(systemUiOverlayStyle);
  }
}
class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {

  var _colorSubscription = null ;
  var _qqLauncher = null ;
  var _phoneLauncher = null ;
  DateTime lastPopTime;
  bool downloading = false ;
  double progress = 0.0 ;

  @override
  void initState() {
    super.initState();
    _colorSubscription = eventBus.on<RouteEvent>().listen((event) {
      Navigator.of(context).pushNamedAndRemoveUntil(event.name ,(route) => route == null,);
    });
    // 调用qq
    _qqLauncher = eventBus.on<QQ>().listen((event) {
      String url = "mqqwpa://im/chat?chat_type=wpa&uin="+event.num+"&version=1&src_type=web&web_src=oicqzone.com" ;
      canLaunch(url).then((result){
        if(result){
          launch(url);
        }else {
          Toast.show('不能访问' , context);
        }
      }) ;
    });
    // 调用电话
    _phoneLauncher = eventBus.on<Phone>().listen((event) {
      String url = "tel:"+event.num ;
      canLaunch(url).then((result){
        if(result){
          launch(url);
        }else {
          Toast.show('不能访问' , context);
        }
      }) ;
    });

    // Navigator.of(context).pushReplacement(MaterialPageRoute(builder: (_){
    //   return UserFullDataPage() ;
    // })) ;
    String d = Config().getUserInfo() ;
    if(d != null){
      dynamic userInfo = jsonDecode(d) ;
      if(userInfo["nickname"] == null || userInfo["nickname"] == ""
        || userInfo["icon"] == null || userInfo["icon"] == "" 
        || userInfo["gender"] == null || userInfo["gender"] == ""){
        //Navigator.of(context).pop() ;
        Navigator.of(context).pushReplacement(MaterialPageRoute(builder: (_){
          return UserFullDataPage() ;
        })) ;
      }
    }

    // 检查更新
    HttpUtil().get(Config().getHost() + "/api/admin/v1/upgrade").then((data) async{
      PackageInfo info = await PackageInfo.fromPlatform() ;
      int version = int.parse(info.buildNumber) ;
      if(data != null){
        if(data["code"] == 200){
          data = data["data"] ;
          data["modifyContent"] = data["modifyContent"].toString().replaceAll("\\r\\n", "\r\n") ;
          int newVersion = data["versionCode"] ;
          if(newVersion > version){
             showDialog(
              context: context ,
              builder: (context){
                return StatefulBuilder(
                  builder: (context , state){
                    return Container(
                      color: Color.fromARGB(0, 0, 0, 0) ,
                      child: AlertDialog(
                        backgroundColor: Color.fromARGB(0, 0, 0, 0),
                        content:  Container(
                          width: ScreenUtil().setWidth(280),
                          height: ScreenUtil().setHeight(360),
                          decoration: BoxDecoration(
                            color: Colors.white ,
                            borderRadius: BorderRadius.all(Radius.circular(12))
                          ),
                          child: Column(
                            // crossAxisAlignment: CrossAxisAlignment.start,
                            children: <Widget>[
                              Container(
                                height: ScreenUtil().setHeight(73),
                                width: ScreenUtil().setWidth(280),
                                child: Image.asset("assets/images/upgrad.png" , fit: BoxFit.fill,),
                              ) ,
                              Container(
                                height: ScreenUtil().setHeight(155),
                                margin: EdgeInsets.only(top:ScreenUtil().setHeight(31) , left:ScreenUtil().setWidth(24) , right:ScreenUtil().setWidth(24)),
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: <Widget>[
                                    Text("更新内容" , style: TextStyle(
                                      fontSize: ScreenUtil().setSp(14) ,
                                      color: Color.fromARGB(255, 19, 28, 53) ,
                                      fontWeight: FontWeight.bold 
                                    ),) ,
                                    Text(data["modifyContent"] , overflow: TextOverflow.ellipsis,style: TextStyle(
                                      fontSize: ScreenUtil().setSp(12) ,
                                      color: Color.fromARGB(255, 78, 86, 108) ,
                                      height: ScreenUtil().setHeight(26) / ScreenUtil().setSp(12)
                                    ),),
                                  ],
                                )
                              ) ,
                              Visibility(
                                visible: !downloading,
                                child: GestureDetector(
                                  child: Container(
                                    margin: EdgeInsets.only(top:ScreenUtil().setHeight(18) , left: ScreenUtil().setWidth(30) , right:ScreenUtil().setWidth(30)),
                                    height: ScreenUtil().setHeight(42),
                                    decoration: BoxDecoration(
                                      color: Color.fromARGB(255, 0, 195, 206) ,
                                      borderRadius: BorderRadius.all(Radius.circular(23))
                                    ),
                                    child: Center(
                                      child: Text("立即更新" , style: TextStyle(
                                        color: Colors.white ,
                                        fontWeight: FontWeight.bold ,
                                        fontSize: ScreenUtil().setSp(14)
                                      ),),
                                    ),
                                  ),
                                  onTap: () async {
                                    state(() {
                                      progress = 0.0 ;
                                      downloading = true ;
                                    });
                                    Dio dio = new Dio() ;
                                    Directory directory = await getExternalStorageDirectory() ;
                                    Directory cache = new Directory(directory.path + "/cache") ;
                                    if(!cache.existsSync()){
                                      cache.createSync() ;
                                    }
                                    Response res = await dio.download(data["downloadUrl"], directory.path + "/cache/"+data["versionName"]+".apk" , onReceiveProgress: (sent , totle){
                                      state((){
                                        progress = sent / totle ;
                                      }) ;
                                    }) ;
                                    if(res.statusCode == 200){
                                      bool permission = await checkPermission() ;
                                      InstallPlugin.installApk(directory.path + "/cache/"+data["versionName"]+".apk" , 'com.mfkb.app')
                                          .then((result) {
                                        print('install apk $result');
                                      }).catchError((error) {
                                        print('install apk error: $error');
                                      });
                                    }
                                  },
                                ),
                              ) ,
                              Visibility(
                                visible: downloading,
                                child:  Container(
                                  margin: EdgeInsets.only(left:ScreenUtil().setWidth(30) , right:ScreenUtil().setWidth(30) , top:ScreenUtil().setHeight(18)),
                                  child: SizedBox(
                                    width: ScreenUtil().setWidth(220),
                                    height: ScreenUtil().setHeight(42),
                                    child: ClipRRect(
                                      borderRadius: BorderRadius.all(Radius.circular(23)) ,
                                      child: LinearProgressIndicator(
                                        backgroundColor: Color.fromARGB(255, 246, 245, 248),
                                        valueColor: AlwaysStoppedAnimation(Color.fromARGB(255, 26, 201, 210)) ,
                                        value: progress,
                                      ),
                                    ),
                                  ),
                                ),
                              ) ,
                              Expanded(
                                child: Column(
                                  children: <Widget>[
                                    Visibility(
                                      visible: !downloading ,
                                      child: GestureDetector(
                                        child: Container(
                                          width: ScreenUtil().setWidth(280),
                                          margin: EdgeInsets.only(top:ScreenUtil().setHeight(12)),
                                          child: Container(
                                            child: Text("跳过此版本" , style: TextStyle(
                                              color: Color.fromARGB(255, 121, 132, 155) ,
                                              fontSize: ScreenUtil().setSp(12)
                                            ),textAlign: TextAlign.center,),
                                          ),
                                        ),
                                        onTap: (){
                                          Navigator.of(context).pop() ;
                                        },
                                      ),
                                    ) ,
                                    Visibility(
                                      visible: downloading ,
                                      child: Container(
                                        width: ScreenUtil().setWidth(280),
                                        margin: EdgeInsets.only(top:ScreenUtil().setHeight(12)),
                                        child: Container(
                                          child: Text("正在更新..." , style: TextStyle(
                                            color: Color.fromARGB(255, 121, 132, 155) ,
                                            fontSize: ScreenUtil().setSp(12)
                                          ),textAlign: TextAlign.center,),
                                        ),
                                      ),
                                    )
                                  ],
                                ),
                              )
                            ],
                          ),
                        ),
                      ),
                    ) ;
                  },
                ) ;
              }
            ) ;
          }
        }
      }
    }) ;
    // update() ;
  }

  void update(check){
    
  }

  Future<bool> checkPermission() async {
    PermissionStatus permission = await PermissionHandler().checkPermissionStatus(PermissionGroup.storage);
    if (permission != PermissionStatus.granted) {
      Map<PermissionGroup, PermissionStatus> permissions =
          await PermissionHandler()
              .requestPermissions([PermissionGroup.storage]);
      if (permissions[PermissionGroup.storage] == PermissionStatus.granted) {
        return true;
      }
    } else {
      return true;
    }
    return false ;
  }

  @override
  Widget build(BuildContext context) {
    ScreenUtil.init(context , width:375 , height:812) ;
    Config().setContext(context) ;
    return Scaffold(
      body: WillPopScope(
        child: Config().getUserInfo() == null || Config().getToken() == null  ? LoginWidge() : NavitorBar() ,
        onWillPop: () async{
          // 点击返回键的操作
          if(lastPopTime == null || DateTime.now().difference(lastPopTime) > Duration(seconds: 2)) {
            lastPopTime = DateTime.now();
            Toast.show('再按一次退出' , context);
          }else{
            lastPopTime = DateTime.now() ;
            // 退出app
            await SystemChannels.platform.invokeMethod('SystemNavigator.pop');
          }
        },
      )  ,
      resizeToAvoidBottomPadding: false ,
    ) ;
  }

  @override
  void dispose() {
    if(_colorSubscription != null){
      _colorSubscription.cancel();
    }
    if(_qqLauncher != null){
      _qqLauncher.cancel() ;
    }
    if(_phoneLauncher != null){
      _phoneLauncher.cancel() ;
    }
    super.dispose();
  }
}